package com.yun.springbootsecurity.config;

import com.yun.springbootsecurity.mapper.PermissionMapper;
import com.yun.springbootsecurity.mapper.ResourceMapper;
import com.yun.springbootsecurity.mapper.RoleMapper;
import com.yun.springbootsecurity.pojo.*;
import com.yun.springbootsecurity.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class MyUserDetailService implements UserDetailsService {

    private final UserService userService;

    private final RoleMapper roleMapper;

    private final PermissionMapper permissionMapper;

    private final ResourceMapper resourceMapper;

    private final PasswordEncoder passwordEncoder;

    public MyUserDetailService(UserService userService, RoleMapper roleMapper, PermissionMapper permissionMapper, ResourceMapper resourceMapper, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.roleMapper = roleMapper;
        this.permissionMapper = permissionMapper;
        this.resourceMapper = resourceMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        User user = userService.selectByUserId(username);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        user.getUserRoleList().forEach(role ->
                roleMapper.selectByRoleId(role.getRoleId()).getRolePermissionList().forEach(permission ->
                        permissionMapper.selectByPermissionId(permission.getPermissionId()).getResourePermissionList().forEach(resourePermission ->
                                resourceMapper.selectResourceByResourceId(resourePermission.getResourceId()).forEach(resource ->
                                        grantedAuthorities.add(new SimpleGrantedAuthority(resource.getResourcePath()))
                                )
                        )
                )
        );
        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),grantedAuthorities);
    }
}
